package Servlet.admin;

import domain.News;
import service.AdminService;
import service.NewsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/newsManagement")
public class NewsManagementServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        Long newsTypeId = 1L;
        Long reqAdminPageIndex = 1L;
        Long pageSize = 7L;
        String value=request.getParameter("search");
        String reqPageIndex=request.getParameter("reqPageIndex");

        if (reqPageIndex != null){
            reqAdminPageIndex = Long.parseLong(reqPageIndex);
        }

        Long adminIndex = (reqAdminPageIndex - 1) * pageSize;

        List<News> newsDataList = AdminService.getNewsData(adminIndex, pageSize);
        int total = AdminService.getNewsTotal();
        Long pageCount = total / pageSize;

        if (total % pageSize != 0) pageCount++;

//        System.out.println(newsDataList);
        request.setAttribute("newsDataList", newsDataList);
        request.setAttribute("total", total);
        request.setAttribute("pageCount", pageCount);
        request.setAttribute("reqAdminPageIndex", reqAdminPageIndex);
        
        if (value != null){
            newsDataList = AdminService.getNewsContentByKeyWord(value);
            request.setAttribute("newsDataList", newsDataList);
            request.setAttribute("total", "");
            request.setAttribute("pageCount", "");
            request.setAttribute("reqAdminPageIndex", "");
        }

        request.getRequestDispatcher("/admin/newsManagement.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
